const axios = require('../../utils/axios');
const app = getApp();

Page({
  data: {
    user: app.globalData.user,
    resume: {}
  },

  onLoad(options) {
    this.getData();
  },

  getData() {
    const header = app.globalData.header;
    const { user } = this.data;
    axios.get('/resume/' + user.id, {}, header).then(res => {
      var { code, data, err } = res;
      console.log(data);
      if(code == 200) {
        if (data.id) {
          data.educationHistory = JSON.parse(data.educationHistory);
          data.workHistory = JSON.parse(data.workHistory);
          data.projectHistory = JSON.parse(data.projectHistory);
          data.awardHistory = JSON.parse(data.awardHistory);
        } else {
          data.fullName = user.familyName + user.lastName;
          data.tel = user.tel;
          data.gender = user.gender;
          data.educationHistory = [];
          data.workHistory = [];
          data.projectHistory = [];
          data.awardHistory = [];
        }
        this.setData({ resume: data });
      } else if(code == 401) {
        app.login(() => this.getData());
      } else throw err;
    }).catch(err => {
      wx.showModal({
        title: '错误',
        content: '获取简历失败：' + JSON.stringify(err),
        showCancel: false
      });
    });
  },

  onConfirm() {
    const header = app.globalData.header;
    var data = this.data.resume;
    const { user } = this.data;
    data.awardHistory = JSON.stringify(data.awardHistory);
    data.educationHistory = JSON.stringify(data.educationHistory);
    data.projectHistory = JSON.stringify(data.projectHistory);
    data.workHistory = JSON.stringify(data.workHistory);
    const oldResume = !!data.id;
    data.id = user.id;
    (oldResume ? axios.put : axios.post)('/resume', data, header).then(res => {
      const { code, data, err } = res;
      console.log(data);
      if(code == 200) {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1500,
          mask: true
        });
        setTimeout(() => {
          this.getData();
        }, 1500);
      } else if(code == 401) {
        app.login(() => this.onConfirm());
      } else throw err;
    }).catch(err => {
      wx.showModal({
        title: '错误',
        content: '修改简历时发生错误：' + JSON.stringify(err),
        showCancel: false
      });
    });
  },

  onInput(e) {
    const { key } = e.currentTarget.dataset;
    const name = 'resume.' + key;
    this.setData({ [name]: e.detail.value });
  },
  onAdd(e) {
    var { resume } = this.data;
    const { key } = e.currentTarget.dataset;
    resume[key].push({});
    this.setData({ resume });
  },
  onDelete(e) {
    wx.showModal({
      title: '提示',
      content: '确认删除？删除后需重新填写',
      complete: (res) => {
        if (res.confirm) {
          var { resume } = this.data;
          const { key, index } = e.currentTarget.dataset;
          resume[key].splice(index, 1);
          this.setData({ resume });
        }
      }
    });
  },
  
})